// pages/sendForum/sendForum.js
var common = require("../../utils/common.js");
//index.js
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    forumList: [],//帖子类别，根据接口获取
    show: '',
    imgs: [],
    downLoad: true,
    textArea: '',//textArea内的内容
    index: '',//发布至的类型
    isSend: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.setNavigationBarTitle({
      title: '新增帖子'
    });
    console.log(app);
    var that = this
    //查询缓存数据
    wx.getStorage({
      key: 'forumTypeList',
      success: function (res) {
        console.log(res.data)
        var forumTypeList = res.data;
        if (forumTypeList && forumTypeList.length > 0) {
          var forumType = [];
          for (var i = 1; i < forumTypeList.length; i++) {
            forumType.push(forumTypeList[i].name);
          }
          that.setData({
            forumList: forumType,
            forumTypeListid: forumTypeList
          })
        } else {
          //缓存中无数据，接口查询。好像可以不用^_^
        }
      }
    });

    wx.getStorage({
      key: 'activeIndex',
      success: function (res) {
        var activeIndex = res.data;
        if (activeIndex == 0) {
          console.log("选择了全部")
          //全部进来的
          that.setData({
            show: true
          })
        } else {
          that.setData({
            show: false,
            activeIndex: activeIndex,
            index: activeIndex - 1
          })
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  /**选择列表 */
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    if (e.detail.value) {
      this.setData({
        index: e.detail.value,
        activeIndex: parseInt(e.detail.value) + 1,
        show: false
      })
      wx.setStorage({
        key: "activeIndex",
        data: this.data.activeIndex
      })
    }
  },
  /**获取textarea的值 */
  bindInputValue: function (e) {
    console.log(e.detail.value);
    this.setData({
      textArea: e.detail.value
    })
  },

  // 上传图片  
  chooseImg: function (e) {
    var that = this;
    var imgs = this.data.imgs;
    if (imgs.length >= 9) {
      this.setData({ lenMore: 1, downLoad: false });
      setTimeout(function () { that.setData({ lenMore: 0 }); }, 2500);
      return false;
    }
    wx.chooseImage({     // count: 1, // 默认9     
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有   
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有    
      success: function (res) {      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片    
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;      // console.log(tempFilePaths + '----');   
        //获取图片后上传到服务器
        console.log(tempFilePaths);
        // for(var i=0;i<tempFilePaths.length;i++){
        //   that.uploadFile(tempFilePaths[i]);
        // }

        for (var i = 0; i < tempFilePaths.length; i++) {
          wx.showLoading({
            title: '加载中',
          })
          console.log("图片地址" + tempFilePaths[i]);
          that.uploadFile(tempFilePaths[i], imgs);
          // if (imgs.length >= 9) {
          //   that.setData({
          //     imgs: imgs
          //    });
          //   return false;
          // } else {
          //   console.log(imgUrl)
          //   imgs.push(imgUrl);
          // }
        }      // console.log(imgs); 

        that.setData({ imgs: imgs });
      }
    });
  },   // 删除图片  
  deleteImg: function (e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs,
      downLoad: true
    });
  },   // 预览图片  
  previewImg: function (e) {     //获取当前图片的下标  
    var index = e.currentTarget.dataset.index;     //所有图片   
    var imgs = this.data.imgs;
    wx.previewImage({     //当前显示图片     
      current: imgs[index],     //所有图片     
      urls: imgs
    })
  },

  uploadFile: function (data, imgs) {
    //图片上传
    var headStr = common.headStr;
    var that = this;
    wx.uploadFile({
      url: headStr + '/portal/wlpForum/xcxUploadFile.action', //仅为示例，非真实的接口地址
      filePath: data,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data"
      },
      success: function (res) {
        console.log(res.data);
        var imgUrl = (res.data.split('"url":"')[1].split('"')[0]);
        if (imgs.length == 9) {
          that.setData({
            downLoad: false
          })
        }
        if (imgs.length >= 9) {
          that.setData({
            imgs: imgs
          });
          return false;
        } else {
          console.log(imgUrl)
          imgs.push(imgUrl);
          that.setData({
            imgs: imgs
          });
          wx.hideLoading()
        }
      }
    })
  },

  send: function () {
    var that = this;
    console.log(that.data.index)
    if (that.data.index === "") {
      wx.showToast({
        title: '请选择发布的类型',
        icon: 'none',
        duration: 2000
      })
    } else if (that.data.textArea == "" && that.data.imgs == "") {
      wx.showToast({
        title: '上传的图片或发布的内容至少选一个',
        icon: 'none',
        duration: 2000
      })
    } else {
      //上传信息
      if (that.data.isSend == true) {
        return false;
      } else {
        that.setData({
          isSend: true
        });
        var position = app.globalData.forumUserInf.position;
        if (!position) {
          position = null;
        }
        common.ajaxPost(
          'portal/wlpForum/addWlpForumInfo.action', {
            bid: app.globalData.bid,
            forumType: that.data.forumTypeListid[parseInt(that.data.index) + 1].id,
            userType: app.globalData.forumUserInf.fouserType,
            userId: app.globalData.forumUserInf.id,
            userName: app.globalData.forumUserInf.name,
            userHeadImg: app.globalData.forumUserInf.headImage,
            title: '标题标题',
            content: that.data.textArea,
            images: (that.data.imgs).join(';'),
            userPosition: position,
            userType: app.globalData.forumUserInf.userType
          },
          function (res) {
            if (res && res.resultCode == "0") {
              wx.showToast({
                title: '帖子发布成功',
                icon: 'none',
                duration: 1500
              });
              setTimeout(function () {
                that.goBack();
              }, 2000)
            }
          }
        )
      }

    }
  },
  goBack: function () {
    var that=this;
    that.setData({
      isSend: true
    });
    wx.navigateBack();
  }
})